//
//  OAuthViewController.swift
//  sinaWeibo
//
//  Created by apple on 15/11/17.
//  Copyright © 2015年 apple. All rights reserved.



import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let client_id = "1238298422"
    
    let redirect_uri = "http://www.itcast.cn"
    
    let client_secret = "f7304b3e043a167f42dbb61ef02dd098"
    
    @objc private func close () {
        //
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    //自动填充用户名密码
    @objc private func autoLoin() {
//        let loin: String = "document.getElementById('userId').value = '15117965568' document.getElementById('passwd').value = 'jpfc6032dfh';"
        let loin:String = "document.getElementById('userId').value = '15117965568' ,document.getElementById('passwd').value = 'jpfc804824586';"
        print("------")
        //执行 js语句
        webView.stringByEvaluatingJavaScriptFromString(loin)
     
    
    }
    
    
    //实例化一个网络浏览器
    let webView = UIWebView()
    
    //让网络浏览器成为控制器的view
    override func loadView() {
        view = webView
        
       webView.delegate = self
        
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        //加载网页
        loadOauthPage()
   
    }
    
    private func setupUI(){
        //创建导航条左边的按钮并添加点击事件
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "close")
        
         self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoLoin")
    
    }
    //加载网络数据
    private func loadOauthPage(){
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        
        let requet = NSURLRequest(URL: url!)
        
        webView.loadRequest(requet)
        
    }

}

//专门处理webView的协议
extension OAuthViewController: UIWebViewDelegate {

    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    
    
    // Optional(http://apisus.wueee.com/c/apisus.php?uid=1687&id=1382&url=http%3A%2F%2Findex.8cnd.com%2Ftj%2F&llurl=&thepage=http://www.itcast.cn/?code=5603ec2d1c949efcf210f5fd7ba67cb7&fuck=1447859795)
    
    //协议方法，如果返回bool，一般表示  如果true表示当前对象可以正常工作，否则不能
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       //absoluteString  获取当彰url的绝对路径
        // let urlString = request.URL?.absoluteString
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        // hasPrefix 检查否包含当前字符串
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        //如果不包含变量redirect_uri的字符返回假
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        //程走到这里，一定包含了回调的url
        // query 表示查询，可以查询当前URL包含的所有参数
        guard let query = request.URL?.query else {
            return false
        }
        
      
        let codeStr = "code="
        //获取 code码
        let code = query.substringFromIndex(codeStr.endIndex)
        
        print(query)
        print(code)
        
        loadAccessToken(code)
        
        return false
        
    }
    
    /*
    OAuth2的access_token接口
    https://api.weibo.com/oauth2/access_token
    
    client_id
    client_secret
    grant_type=authorization_code
    code
    redirect_uri
    */

    private func loadAccessToken(code:String){
        
        let URLString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
    
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFN.POST(URLString, parameters: parameters, success: { (_, result) -> Void in
            if let dict = result as? [String: AnyObject]{
                print(result)
                //字典转模型
                let account = UseAccount(dict: dict)
                 print("+++++++++++++++++++++++++")
                print(account)
                
                let access_token = dict["access_token"] as? String
                let uid = dict["uid"] as? String
                self.loadUserInfo(access_token!, uid: uid!)
          
            }
    
            }) { (_, error) -> Void in
            print(error)
        }
    
    }
    
    //获取用户作息方法
    /*
    https://api.weibo.com/2/users/show.json
    HTTP请求方式 GET
    access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
    uid	            false	int64	需要查询的用户ID
    */
    
    private func loadUserInfo(access_token:String, uid:String){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":access_token, "uid":uid]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, success: { (_, relule) -> Void in
            
            print(relule)
            
            }) { (_, error) -> Void in
                print(error)
        }
        
        
    
    }

}
